import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.GoodsInfo.pojo.GoodEase
import com.example.idlefish.Message.MessageChatActivity
import com.example.idlefish.Message.MessagePreviewData
import com.example.idlefish.PublicModule.ApplicationConst
import com.example.idlefish.PublicModule.ApplicationConst.NetRequestForGoodContext
import com.example.idlefish.PublicModule.UserConst
import com.example.idlefish.R
import okhttp3.Callback
import okhttp3.Response
import org.json.JSONObject
import java.io.IOException
import java.io.Serializable

class MessagePreviewAdapter(private val messageList: MutableList<MessagePreviewData>) : RecyclerView.Adapter<MessagePreviewAdapter.MessageViewHolder>() {

    class MessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val userName: TextView = itemView.findViewById(R.id.message_userName)
        val messagePreview: TextView = itemView.findViewById(R.id.message_preview)
        val lastTime: TextView = itemView.findViewById(R.id.message_lastTime)
        val thisItem: LinearLayout = itemView.findViewById(R.id.message_item_thisItem)
        val avatar : ImageView = itemView.findViewById(R.id.imageView_message_preview_avatar)
}

    fun updatePreviews(newData: List<MessagePreviewData>) {
        messageList.clear()
        messageList.addAll(newData) 
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.message_main_item, parent, false)
        return MessageViewHolder(view)
    }

    override fun onBindViewHolder(holder: MessageViewHolder, position: Int) {
        val messageItem = messageList[position]
        holder.messagePreview.text = messageItem.messageContent
        holder.lastTime.text = messageItem.messageLastTime
        if (messageItem.senderID == UserConst.id.toInt()) {
            holder.userName.text = messageItem.receiverName
            if (messageItem.receiverAvatar != null) {
                holder.avatar.setImageBitmap(ApplicationConst.decodeBase64ToImage(holder.itemView.context, messageItem.receiverAvatar))
            } else {
                holder.avatar.setImageResource(R.drawable.default_image)
            }
        } else {
            holder.userName.text = messageItem.senderName
            if (messageItem.senderAvatar != null) {
                holder.avatar.setImageBitmap(ApplicationConst.decodeBase64ToImage(holder.itemView.context, messageItem.senderAvatar))
            } else {
                holder.avatar.setImageResource(R.drawable.default_image)
            }
        }

        // Request product image and display it
        val productId = messageItem.messageContentPhoto
        if (!productId.isNullOrEmpty()) {
            val cleanedProductId = productId.replace("[^\\d]".toRegex(), "")
            val productIdLong = cleanedProductId.toLong()
            NetRequestForGoodContext(productIdLong, object : Callback {
                override fun onFailure(call: okhttp3.Call, e: IOException) {
                    println("请求失败: ${e.message}")
                }

                override fun onResponse(call: okhttp3.Call, response: Response) {
                    response.use {
                        if (!response.isSuccessful) {
                            println("请求失败，状态码: ${response.code}")
                            return
                        }

                        val responseBody = response.body?.string()
                        if (responseBody != null) {
                            try {
                                val jsonObject = JSONObject(responseBody)
                                val queryGoodResponse = jsonObject.getJSONObject("queryGoodResponse")
                                val picEncodingList = queryGoodResponse.getJSONArray("picEncodeingList")
                                val base64Image = picEncodingList.getString(0)
                                val imageByteArray = android.util.Base64.decode(base64Image, android.util.Base64.DEFAULT)

                                // (holder.itemView.context as Activity).runOnUiThread {
                                //     holder.goodPicture.setImageBitmap(BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.size))
                                // }
                            } catch (e: Exception) {
                                println("解析 JSON 失败: ${e.message}")
                            }
                        }
                    }
                }
            })
        }

        holder.thisItem.setOnClickListener {
            val intent = Intent(holder.itemView.context, MessageChatActivity::class.java)
            intent.putExtra("messageInfo", messageItem as Serializable)
            val goodInfo = GoodEase(-1, -1f, "",-1f)
            intent.putExtra("goodInfo", goodInfo as Serializable)
            holder.thisItem.context.startActivity(intent)
        }
    }

    override fun getItemCount() = messageList.size
}